package prop

import (
	"bufio"
	"io"
	"os"
	"regexp"
	"strings"
)

var properties map[string]string

func GetProp(key string) string {
	if value, ok := properties[key]; ok {
		return value
	} else {
		return "Key Not Found"
	}
}

func GetProperties() map[string]string {
	return properties
}

func Init(filePath string) {
	//logger.Info("----------------配置文件开始加载------------------")
	properties = make(map[string]string)
	file, err := os.Open(filePath)
	defer file.Close()
	reader := bufio.NewReader(file)
	if err != nil {
		//logger.Error(err.Error())
	}
	for {
		b, isprefix, err := reader.ReadLine()
		if err != nil && err != io.EOF {
			//logger.Error(err.Error())
		}
		if err == io.EOF {
			break
		}
		regp, err := regexp.Compile(`#[\s\S]*`)
		if err != nil {
			//logger.Error(err.Error())
		}
		var appendLine, temp string = "", ""
		if isprefix {
			temp = ""
			temp = string(b)
		} else {
			temp += string(b)
		}
		appendLine = temp
		if len(appendLine) > 0 && !regp.MatchString(appendLine) {
			//regp, err := regexp.Compile(`[\s\S]`)
			//第一个=的索引
			index := strings.Index(appendLine, "=")
			//string转[]byte
			b := []byte(appendLine)
			properties[string(b[0:index])] = string(b[index+1:])
		}
	}
	//logger.Info("----------------配置文件加载成功------------------")
}
